<script setup lang="ts">
import { uploadAPI } from "@/apis/common";
import { addEnterpriseAPI, getEnterpriseDetailAPI, getIndustryListAPI, updateEnterpriseAPI } from "@/apis/enterprise";
import type { EnterpriseParams, Industry } from "@/types/enterprise";
import {  ElMessage, type FormInstance, type FormRules, type UploadRawFile, type UploadRequestOptions, type UploadUserFile } from "element-plus";
import { CircleCheck, Upload } from '@element-plus/icons-vue'
import { computed, onMounted, ref } from "vue";
import { useRoute, useRouter } from "vue-router";

// 根据接口文档定义字段，用于表单双向绑定
const addForm = ref<EnterpriseParams>({
  name: "", // 企业名称
  legalPerson: "", // 法人
  registeredAddress: "", // 注册地址
  industryCode: undefined, // 所在行业
  contact: "", // 企业联系人
  contactNumber: "", // 联系人电话
  businessLicenseUrl: "", // 营业执照url
  businessLicenseId: 0, // 营业执照id
});

const industryList = ref<Industry[]>([]); // 可选行业列表
const getIndustryList = async () => {
  const res = await getIndustryListAPI();
  industryList.value = res.data;
};
getIndustryList();

// 营业执照
const fileList = ref<UploadUserFile[]>([]);

// 上传营业执照
const uploadFile = async (options: UploadRequestOptions) => {
  console.log("上传营业执照", options);
  //1.准备formData对象
  const fd = new FormData();
  //2.根据后端要求准备字段
  fd.append("file", options.file);
  fd.append("type", "businessLicense");
  // 3. 调用接口上传文件
  const res = await uploadAPI(fd);
  addForm.value.businessLicenseUrl = res.data.url
  addForm.value.businessLicenseId = res.data.id
  ruleForm.value?.validateField("businessLicenseUrl")

  //return图片路径
  return res.data.url;
};

//删除营业执照
const deleteFile = () => {
  addForm.value.businessLicenseUrl = ""
  addForm.value.businessLicenseId = undefined
  //单独校验表单
  ruleForm.value?.validateField("businessLicenseUrl")
}


//在before-upload钩子中限制用户上传文件的格式和大小
const beforeUpload = (rawFile:UploadRawFile)=>{
  // size 的单位是 Byte
  // 5M = 5 * 1024 * 1024
  if(rawFile.size > 5 * 1024 * 1024){
    ElMessage.error('上传文件大小不能超过5M')
    return false
  }else if(['image/jpeg','image/png'].includes(rawFile.type)===false){
    ElMessage.error('上传文件格式不正确')
    return false
  }
  return true// 返回true表示上传成功
}


  // 表单组件实例，用于 表单整体校验 和 表单重置
  const ruleForm = ref<FormInstance>()

  // 表单校验规则
  const addRules = ref<FormRules<EnterpriseParams>>({
    name: [
      { required: true, message: '请输入企业名称', trigger: 'blur' },
      { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
    ],  
    legalPerson: [
      { required: true, message: '请输入法人', trigger: 'blur' },
      { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
    ],
    registeredAddress: [
      { required: true, message: '请输入注册地址', trigger: 'blur' },
      { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
    ],
    industryCode: [
      { required: true, message: '请选择所在行业', trigger: 'blur' }
    ],
    contact: [
      { required: true, message: '请输入企业联系人', trigger: 'blur' },
      { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
    ],
    contactNumber: [
      { required: true, message: '请输入联系电话', trigger: 'blur' },
      { pattern: /^1[3-9]\d{9}$/, message: "请输入正确的手机号", trigger: 'blur' },    
    ],
    businessLicenseUrl: [
      { required: true, message: '请上传营业执照', trigger: 'blur' }
    ]
  })


  //路由
  const router = useRouter()

// 提交状态
const submitLoading = ref(false)

  //确认提交
  const handleAddEnterprise = async () => {
    try {
        submitLoading.value = true
        await ruleForm.value?.validate()
        if(id.value){
          await updateEnterpriseAPI({
            ...addForm.value,
            id: Number(id.value)
          })
          ElMessage.success("编辑企业成功")
        }else{
          //提交时使用.value获取实际值
          await addEnterpriseAPI(addForm.value)
          ElMessage.success("添加企业成功")
        }
        router.back()
    } catch(err) {
        submitLoading.value = false
    }
  }


  // 重置表单
  const resetForm = () => {
    ruleForm.value?.resetFields()
  }

  // 获取路由参数
  const route = useRoute()

  const id = computed(()=>{
    return route.params.id as string
  })

  // 有合同id 调用详情接口
  const getEnterpriseDetail = async () => {
    const res = await getEnterpriseDetailAPI(id.value)
    const { businessLicenseId, businessLicenseUrl, contact, contactNumber, industryCode, legalPerson, name, registeredAddress, businessLicenseName } = res.data
    addForm.value = { businessLicenseId, businessLicenseUrl, contact, contactNumber, industryCode, legalPerson, name, registeredAddress }
    fileList.value.push({
      name: businessLicenseName,
      url: businessLicenseUrl
    })
  }

  onMounted(()=>{
    // 有合同id 调用详情接口
    if (id.value) {
      getEnterpriseDetail()
    }
  })



</script>

<template>
  <div class="add-enterprise">
    <header class="add-header">
      <el-page-header :content="$route.params.id ? '编辑企业' : '添加企业'" @back="$router.back()" />
    </header>
    <main class="add-main">
      <div class="form-container">
        <div class="title">企业信息</div>
        <div class="form">
          <el-form 
          ref="ruleForm" 
          label-width="100px"
          :model="addForm"
          :rules="addRules"
          >
            <el-form-item label="企业名称" prop="name">
              <el-input v-model="addForm.name" />
            </el-form-item>
            <el-form-item label="法人" prop="legalPerson">
              <el-input v-model="addForm.legalPerson" />
            </el-form-item>
            <el-form-item label="注册地址" prop="registeredAddress">
              <el-input v-model="addForm.registeredAddress" />
            </el-form-item>
            <el-form-item label="所在行业" prop="industryCode">
              <el-select v-model="addForm.industryCode">
                <el-option
                  v-for="item in industryList"
                  :key="item.industryCode"
                  :value="item.industryCode"
                  :label="item.industryName"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="企业联系人" prop="contact">
              <el-input v-model="addForm.contact" />
            </el-form-item>
            <el-form-item label="联系电话" prop="contactNumber">
              <el-input v-model="addForm.contactNumber" />
            </el-form-item>
            <el-form-item label="营业执照" prop="businessLicenseUrl">
              <el-upload
                :http-request="uploadFile"
                list-type="picture"
                :limit="1"
                v-model:file-list="fileList" 
                :before-upload="beforeUpload"
                accept="..png, .jpg, .jpeg" 
                @remove="deleteFile"
              >
                <el-button
                  v-if="fileList.length === 0"
                  type="primary"
                  :icon="Upload"
                  >
                  上传文件</el-button>
                <el-button 
                v-else type="success" 
                :icon="CircleCheck" 
                disabled
                  >已上传</el-button>
                <template #tip>
                  <div class="el-upload__tip">
                    支持扩展名：.png .jpg .jpeg, 文件大小不得超过5M
                  </div>
                </template>
              </el-upload>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </main>
    <footer class="add-footer">
      <div class="btn-container">
        <el-button @click="resetForm()" :disabled="id.length !==0">重置</el-button>
        <el-button type="primary" @click="handleAddEnterprise" :loading="submitLoading">
          {{ submitLoading ? '提交中...' : '确定' }}
        </el-button>
      </div>
    </footer>
  </div>
</template>

<style scoped lang="scss">
.add-enterprise {
  background-color: #f4f6f8;
  height: 100vh;

  .add-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 20px;
    height: 64px;
    line-height: 64px;
    font-size: 16px;
    font-weight: bold;
    background-color: #fff;

    .left {
      span {
        margin-right: 4px;
      }

      .arrow {
        cursor: pointer;
      }
    }

    .right {
      text-align: right;
    }
  }

  .add-main {
    background: #f4f6f8;
    padding: 20px 130px;

    .form-container {
      background-color: #fff;

      .title {
        height: 60px;
        line-height: 60px;
        padding-left: 20px;
      }

      .form {
        margin-bottom: 20px;
        padding: 20px 65px 24px;

        .el-form {
          display: flex;
          flex-wrap: wrap;

          .el-form-item {
            width: 50%;
          }
        }
      }
    }
  }

  .add-footer {
    position: fixed;
    bottom: 0;
    width: 100%;
    padding: 24px 50px;
    color: #000000d9;
    font-size: 14px;
    background: #fff;
    text-align: center;
  }
}
</style>
